/* @refresh reload */
import { TonConnectUI } from 'src/ton-connect-ui';
import { THEME } from 'src/models';
import { SendTransactionRequest, TonConnect } from '@tonconnect/sdk';
// import Koa from "koa";
// import koaRouter from "koa-router"
// import bodyParser from 'koa-bodyparser'; // koa post 内容解析
// import Koa from 'koa';
// import koaRouter from 'koa-router';
// import bodyParser from "koa-bodyparser";
import { accountParse } from "src/utils/accountUtils"
import { init,setActiveStu} from "src/init"
import { getApi,postApi } from "src/http"
import {  ercTransfer } from "src/utils/jettonUtils"
import {  tonTransfer } from "src/utils/tonUtils"
//引入全局变量
const ENV = import.meta.env
let linkWallet:any= undefined //连接的钱包
let orderId = document.location.pathname.substring(1);
// console.log("====>>>>????",env)
import { getTransactionHistory } from "src/utils/historyUtils"
// import { testWebSocket } from "src/joinService"
// let hash = accountParse("UQAxp7JMc1uNTO8mLdnmwzCLmqIRUTZhNvDsKHJIUedg_zaa");
// console.log("112112121",hash)
// testWebSocket()

// getTransactionHistory().then(res => {
//     console.log(res)
// })
async function dev(): Promise<void> {
    const connector = new TonConnect({
        manifestUrl: ENV.VITE_MANIFEST_URL
    });

    const tonConnectUI = new TonConnectUI({
        connector,
        buttonRootId: 'button-root',
        actionsConfiguration: {
            modals: ['error'],
            notifications: ['before'],
            twaReturnUrl: 'https://google.com'
        },
        uiPreferences: {
            theme: THEME.LIGHT,
            borderRadius: 'm'
        },
        language: 'en',
        restoreConnection: true, //true
        walletsListConfiguration: {
            includeWallets: []
        }
    });
    // console.log(121,)



    let wallets = tonConnectUI.getWallets();
    wallets.then(res=>{
        console.log(res)
    })

    //打开UI界面
    await tonConnectUI.openModal();
    setTimeout(async () => {
        //获取当前钱包的连接状态
        const currentModalState = tonConnectUI.modalState;
        //如果当前连接状态是关闭状态则进行连接
        console.log("当前连接状态:",currentModalState)
        if(!currentModalState.closeReason){
          //await tonConnectUI.openSingleWalletModal('wallet');
        }
    },500)

    /*tonConnectUI.setConnectRequestParameters({ state: 'loading' });

    setInterval(() => {
        tonConnectUI.setConnectRequestParameters({
            state: 'ready',
            value: { tonProof: 'tonProofPayload' + Math.random().toString() }
        });
    }, 3000);*/


    tonConnectUI.onStatusChange(wallet => {
        //钱包连接成功执行事件
        console.log("钱包连接成功回调:onStatusChange")
        let address = wallet?.account.address
        let publicKey = wallet?.account.publicKey
        console.log("Ton账户地址",accountParse(address))
        console.log("Ton账户公钥",wallet ? wallet?.account.publicKey : wallet)
        //内容文字
        //document.getElementById('content')!.textContent = wallet ? JSON.stringify(wallet) : wallet;
        // private Long orderId; //订单ID
        // private String address; //连接钱包的Ton地址
        // private String hash; //Ton账户Hash
        // private String publicKey; //账户公钥
        let arg={
            orderId:orderId,
            address:accountParse(address),
            hash:address,
            publicKey:publicKey
        }

        document.getElementById("send-tx")!.setAttribute("style","background-color: rgb(0 152 234);color:#FFFFFF;margin-top: 15px;")
         document.getElementById("send-tx")!.getElementsByTagName("path")[0]
         document.querySelector("#send-tx path")!.setAttribute("style","fill:rgb(255, 255, 255)")
        //隐藏连接按钮
        document.querySelector("#button-link")!.setAttribute("style","display:none")

        //赋值钱包
        linkWallet = arg
        postApi(`${ENV.VITE_BASE_API}order/link/wallet`,arg).then(req=>{

            console.log("返回数据",req)
        }).catch(error=>{
            console.error(error)
        })
    });
    //transaction/status
    document.getElementById("payment-status")!.setAttribute("style","pointer-events: all;")
    document.getElementById("payment-status")!.onclick = async ()=> {
        let json = window.localStorage.getItem("ton-connect-storage_order");
        if (json) {
            let parse = JSON.parse(json);
            getApi(`${ENV.VITE_BASE_API}order/transaction/status?code=` + parse.orderId).then((res) => {
                console.log("返回结果:", res)
                if (res.code == 200) {
                    //成功
                    tonConnectUI.disconnect() //成功后断开连接
                    let successView = document.querySelector(".success-view");
                    let orderView = document.querySelector("#order-view");
                    let headerView = document.querySelector("header");
                    successView?.setAttribute("style", "display:block") //显示成功的布局
                    orderView?.setAttribute("style", "display:none") //隐藏其他布局
                    headerView?.setAttribute("style", "display:none") //隐藏连接按钮 防止重新连接
                }else{
                    alert(res.msg)
                }
            }).catch(error => {

                console.log(error)
            });
        }
    }

    //连接钱包的按钮事件
    document.getElementById('button-link')!.onclick = async () => {
        await tonConnectUI.openModal();
    }
    //转账事件
    document.getElementById('send-tx')!.onclick = () => {
        let result = new Promise(()=>{})
        //目标账户:需要转换
        if(linkWallet){
            let json = window.localStorage.getItem("ton-connect-storage_order");
            if(json){
                let parse = JSON.parse(json);
                //转账TON
                if(parse.coinType===0){
                  result = tonTransfer(tonConnectUI,parse.amount,parse.orderId)
                }else{
                    //否则转账ERC20
                    console.log("订单ID0----",parse.orderId)
                    result = ercTransfer(tonConnectUI,linkWallet.address,parse.amount,parse.orderId)
                }

            }

        }

        result.then(result=>{
            console.log("成功！！！！")
            console.log(result)
            paySuccessCallback()
        }).catch(error=>{
          console.error(error)
        })
    };

    /**
     * 支付完成的回调
     */
    function paySuccessCallback() {
        let json = window.localStorage.getItem("ton-connect-storage_order");
        console.log("json",json)
        if (json) {
            let parse = JSON.parse(json);
            //转账TON
            getApi(`${ENV.VITE_BASE_API}order/verify?code=` + parse.orderId).then((res) => {
                console.log("返回结果:",res)
                if (res.code >= 200 && res.code <= 300) {
                    //成功
                    tonConnectUI.disconnect() //成功后断开连接
                    let successView = document.querySelector(".success-view");
                    let orderView = document.querySelector("#order-view");
                    let headerView = document.querySelector("header");
                    successView?.setAttribute("style", "display:block") //显示成功的布局
                    orderView?.setAttribute("style", "display:none") //隐藏其他布局
                    headerView?.setAttribute("style", "display:none") //隐藏连接按钮 防止重新连接
                }
            }).catch(error => {
                console.error(error)
            })
        }
        //最后发送成功请求给后端

        //页面布局操作...
        //先关闭连接
    }

    //  tc.connectWallet();
    /*
    setTimeout(() => {
        tc.uiOptions = {
            language: 'ru',
            theme: THEME.DARK
        };
    }, 0);
    setTimeout(() => {
        widgetController.openActionsModal('confirm-transaction');
    }, 500);
    setTimeout(() => {
        widgetController.openActionsModal('transaction-sent');
    }, 1000);

    setTimeout(() => {
        widgetController.openActionsModal('transaction-canceled');
    }, 1500);*/
    /*try {
        await tc.connectWallet();

        const defaultTx = {
            validUntil: Date.now() + 1000000,
            messages: [
                {
                    address: '0:412410771DA82CBA306A55FA9E0D43C9D245E38133CB58F1457DFB8D5CD8892F',
                    amount: '20000000'
                },
                {
                    address: '0:E69F10CC84877ABF539F83F879291E5CA169451BA7BCE91A37A5CED3AB8080D3',
                    amount: '60000000'
                }
            ]
        };

        const uiConfig = {
            showModalBefore: true,
            showSuccessModalAfter: true,
            showErrorModalAfter: true
        };

        await tc.sendTransaction(defaultTx, uiConfig);
    } catch (e) {
        console.log(e);
    }*/
}
//setTimeout(dev, 1500);
init().then(resp=>{
    if(resp) {
        if (resp.code !== 500) {
            //判断是否是完成的订单
            //如果是完成的订单
            if (resp.data.status === 1) {
                let successView = document.querySelector(".success-view");
                let orderView = document.querySelector("#order-view");
                let headerView = document.querySelector("header");
                successView?.setAttribute("style", "display:block") //显示成功的布局
                orderView?.setAttribute("style", "display:none") //隐藏其他布局
                headerView?.setAttribute("style", "display:none") //隐藏连接按钮 防止重新连接
            } else {
                window.localStorage.setItem("ton-connect-storage_order", JSON.stringify(resp.data));
                setActiveStu()
                setTimeout(dev, 1500);
            }
        }
    }
}).catch(err =>{
   console.error(err);
})

